// NBA相关API服务
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'nba_models.dart';

class NbaService {
  static final Map<String, String> _headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Accept': 'application/json',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
  };

  /// 获取NBA直播比赛列表
  static Future<List<NbaLiveMatch>> fetchLiveMatches({DateTime? date, SportType? sportType}) async {
    try {

      final results = await Future.wait([
        _fetchKanqiubaLiveMatches(date: date, isfinished: 2, sportType: sportType),
        _fetchKanqiubaLiveMatches(date: date, isfinished: 0, sportType: sportType),
      ], eagerError: false);
      
      // 合并结果，去重
      final allMatches = <NbaLiveMatch>[];
      final seenIds = <String>{};
      
      for (final result in results) {
        if (result != null) {
          for (final match in result) {
            if (!seenIds.contains(match.id)) {
              allMatches.add(match);
              seenIds.add(match.id);
            }
          }
        }
      }  
      return allMatches;
    } catch (e) {
      print('获取NBA直播比赛失败: $e');
      return [];
    }
  }
  
  /// 从虎扑体育获取直播比赛
  static Future<List<NbaLiveMatch>?> _fetchHupuLiveMatches() async {
    print('开始获取虎扑数据...');
    try {
      final response = await http.get(
        Uri.parse('https://nba.hupu.com/api/live/matches'),
        headers: _headers,
      ).timeout(const Duration(seconds: 10));
      
      if (response.statusCode == 200) {
        print('虎扑数据获取成功: ${response.body}');
        return NbaDataSourceParser.parseHupuMatches(response.body);
      }
    } catch (e) {
      print('虎扑直播数据获取失败: $e');
    }
    return null;
  }
  
  /// 从JRS直播获取直播比赛
  static Future<List<NbaLiveMatch>?> _fetchJrsLiveMatches() async {
    print('开始获取JRS数据...');
    try {
      final response = await http.get(
        Uri.parse('https://www.jrszb.com/api/nba/live'),
        headers: _headers,
      ).timeout(const Duration(seconds: 10));
      if (response.statusCode == 200) {
        print('JRS数据获取成功: ${response.body}');
        return NbaDataSourceParser.parseJrsMatches(response.body);
      }
    } catch (e) {
      print('JRS直播数据获取失败: $e');
    }
    return null;
  }
  
  /// 从说球帝直播获取直播比赛
  static Future<List<NbaLiveMatch>?> _fetchShuoqiudiLiveMatches() async {
    print('开始获取说球帝数据...');
    try {
      final response = await http.get(
        Uri.parse('https://shuoqiudi-tv.net/api/sports/nba'),
        headers: _headers,
      ).timeout(const Duration(seconds: 10));
      
      if (response.statusCode == 200) {
        print('从说球帝直播获取成功 ${response.body}');
        return NbaDataSourceParser.parseShuoqiudiMatches(response.body);
      }
    } catch (e) {
      print('从说球帝直播获取失败: $e');
    }
    return null;
  }

  /// 从看球吧获取直播比赛
  static Future<List<NbaLiveMatch>?> _fetchKanqiubaLiveMatches({DateTime? date, int? isfinished, SportType? sportType}) async {
    print('开始获取看球吧数据...');
    try {
      // 获取指定日期或当前日期
      final targetDate = date ?? DateTime.now();
      final dateStr = '${targetDate.year}-${targetDate.month.toString().padLeft(2, '0')}-${targetDate.day.toString().padLeft(2, '0')}';
      
      // 构建请求体，根据赛事类型设置相应的eventids字段
      final body = {
        "date": dateStr,
        "size": 50,
        "isfinished": isfinished,
        "ishot": 1,
        "detail": 1,
        "basketball_eventids": sportType == SportType.all || sportType == SportType.basketball ? 0 : -1,
        "football_eventids": sportType == SportType.all || sportType == SportType.football ? 0 : -1,
        "league_eventids": sportType == SportType.all || sportType == SportType.lol ? 0 : -1,
        "kog_eventids": sportType == SportType.all || sportType == SportType.kog ? 0 : -1,
        "csgo_eventids": sportType == SportType.all || sportType == SportType.csgo ? 0 : -1,
        "dota2_eventids": sportType == SportType.all || sportType == SportType.dota2 ? 0 : -1,
        "multiple_days": 0,
        "use_recommend": 0,
        "isfc": 0,
        "sp_source": "11",
        "token": "1LEU7UHLXFUBOVUHUV3ALQSP18HGEDN3",
        "uid": "1584006",
        "platform": 0
      };
      print('看球吧body: $body');
      final response = await http.post(
        Uri.parse('https://zhiboapi3003.zb6.fun/api/race/getDateMatch2'),
        headers: {
          ..._headers,
          'Content-Type': 'application/json',
        },
        body: json.encode(body),
      ).timeout(const Duration(seconds: 15));
      
      if (response.statusCode == 200) {
        print('看球吧数据获取成功: ${response.statusCode}');
        return NbaDataSourceParser.parseKanqiubaMatches(response.body);
      } else {
        print('看球吧API请求失败: ${response.statusCode}');
      }
    } catch (e) {
      print('看球吧直播数据获取失败: $e');
    }
    return null;
  }

  /// NBA中国获取NBA赛程列表
  static Future<List<NbaSchedule>> fetchSchedules({DateTime? startDate, DateTime? endDate}) async {
    try {
      // 设置默认日期范围（当前日期）
      final now = DateTime.now();
      final start = startDate ?? now.subtract(const Duration(days: 0));
      final end = endDate ?? now.add(const Duration(days: 0));
      
      // 格式化日期
      final startStr = _formatDate(start);
      final endStr = _formatDate(end);
      
      // 构建API URL
      final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
      final url = Uri.parse(
        'https://api.nba.cn/sib/v2/game/schedule?'
        'app_key=tiKB2tNdncnZFPOi&'
        'app_version=1.1.0&'
        'channel=NBA&'
        'device_id=c263274b75182ba88d82184208ee88a2&'
        'end=$endStr&'
        'install_id=2023821643&'
        'network=N%2FA&'
        'os_type=3&'
        'os_version=1.0.0&'
        'sign=sign_v2&'
        'sign2=0576745EB1E18C8BA6BDCB1744B0FF5FE30A6FAD7589D951D2185E102FF88011&'
        'start=$startStr&'
        't=$timestamp'
      );
      
      print('获取NBA赛程: $url');
      
      final response = await http.get(url, headers: _headers)
          .timeout(const Duration(seconds: 15));
      
      if (response.statusCode == 200) {
        // 使用解析器解析赛程数据
        final schedules = NbaDataSourceParser.parseNbaCnSchedules(response.body);
        
        if (schedules.isNotEmpty) {
          return schedules;
        }
        
        // 如果解析失败，返回模拟数据
        return _getMockSchedules();
      } else {
        print('NBA赛程API请求失败: ${response.statusCode}');
        return _getMockSchedules();
      }
    } catch (e) {
      print('获取NBA赛程失败: $e');
      return _getMockSchedules();
    }
  }
  
  /// 格式化日期为 yyyy-MM-dd
  static String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }
  
  /// 获取模拟赛程数据作为fallback
  static List<NbaSchedule> _getMockSchedules() {
    final now = DateTime.now();
    return [
    ];
  }
  
  /// 获取NBA新闻资讯
  static Future<List<NbaNews>> fetchNews({int ? page, int ? limit}) async {
    try {
      // 首先尝试从NBA中国官网获取真实新闻数据
      final nbaCnNews = await _fetchNbaCnNews(page ?? 1, limit ?? 20);
      if (nbaCnNews.isNotEmpty) {
        return nbaCnNews;
      }
      
      // 如果NBA中国官网获取失败，尝试从虎扑获取
      final hupuNews = await _fetchHupuNews( page ?? 1, limit ?? 20);
      if (hupuNews.isNotEmpty) {
        return hupuNews;
      }
      
      // 如果获取真实数据都失败，返回模拟数据作为fallback
      await Future.delayed(const Duration(milliseconds: 300));
      
      return [
      ];
    } catch (e) {
      print('获取NBA新闻失败: $e');
      return [];
    }
  }

  /// 从虎扑体育获取新闻
  static Future<List<NbaNews>> _fetchHupuNews(int page, int limit) async {
    try {
      final response = await http.get(
        Uri.parse('https://nba.hupu.com/api/news?page=$page&limit=$limit'),
        headers: _headers,
      ).timeout(const Duration(seconds: 10));
      
      if (response.statusCode == 200) {
        return NbaDataSourceParser.parseHupuNews(response.body);
      }
    } catch (e) {
      print('虎扑新闻数据获取失败: $e');
    }
    return [];
  }

  /// 获取NBA集锦视频
  static Future<List<NbaHighlight>> fetchHighlights({int ? page, int ? limit}) async {
    try {
      page = page ?? 1;
      limit = limit ?? 20;
      final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
      final url = Uri.parse(
          'https://api.nba.cn/cms/v2/web/column/modules/list?'
          'app_key=tiKB2tNdncnZFPOi&'
          'app_version=1.1.0&'
          'channel=NBA&'
          'device_id=c263274b75182ba88d82184208ee88a2&'
          'install_id=2023821643&'
          'network=N%2FA&'
          'os_type=3&'
          'os_version=1.0.0&'
          'page_no=$page&'
          'page_size=$limit&'
          'page_type=3&'
          'sign=sign_v2&'
          'sign2=0576745EB1E18C8BA6BDCB1744B0FF5FE30A6FAD7589D951D2185E102FF88011&'
          't=$timestamp'
      );
      print('获取NBA集锦视频列表url: $url');
  
      final response = await http.get(url, headers: _headers)
          .timeout(const Duration(seconds: 15));
      print('获取Nba集锦视频列表响应code: ${response.statusCode}');
      if (response.statusCode == 200) {
        return NbaDataSourceParser.parseNbaCnHighlights(response.body);
      } else {
        print('获取NBA集锦失败: HTTP ${response.statusCode}');
        return [];
      }
    } catch (e) {
      print('获取NBA集锦失败: $e');
      return [];
    }
  }

    /// 获取NBA集锦更多视频
  static Future<List<NbaHighlight>> fetchHighMorelights({int ? page, int ? limit}) async {
    try {
      page = page ?? 1;
      limit = limit ?? 20;
      final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
      final url = Uri.parse(
          'https://api.nba.cn/cms/v2/web/column/modules/list?'
          'app_key=tiKB2tNdncnZFPOi&'
          'app_version=1.1.0&'
          'channel=NBA&'
          'device_id=c263274b75182ba88d82184208ee88a2&'
          'install_id=2023821643&'
          'module_id=9999998&'
          'network=N%2FA&'
          'os_type=3&'
          'os_version=1.0.0&'
          'page_no=$page&'
          'page_size=$limit&'
          'page_type=3&'
          'sign=sign_v2&'
          'sign2=0576745EB1E18C8BA6BDCB1744B0FF5FE30A6FAD7589D951D2185E102FF88011&'
          't=$timestamp'
      );
      print('获取NBA集锦视频列表url: $url');
  
      final response = await http.get(url, headers: _headers)
          .timeout(const Duration(seconds: 15));
      print('获取Nba集锦视频列表响应code: ${response.statusCode}');
      if (response.statusCode == 200) {
        return NbaDataSourceParser.parseNbaCnHighlights(response.body);
      } else {
        print('获取NBA集锦失败: HTTP ${response.statusCode}');
        return [];
      }
    } catch (e) {
      print('获取NBA集锦失败: $e');
      return [];
    }
  }


  /// 获取NBA纪录片
  static Future<List<NbaDocumentary>> fetchDocumentaries({int page = 1, int limit = 20}) async {
    try {
      // 模拟数据
      await Future.delayed(const Duration(milliseconds: 500));
      
      return [

      ];
    } catch (e) {
      print('获取NBA纪录片失败: $e');
      return [];
    }
  }

  /// 获取NBA球队排名
  static Future<List<NbaTeam>> fetchTeamStandings() async {
    try {
      // 模拟数据
      await Future.delayed(const Duration(milliseconds: 300));
      
      return [
      ];
    } catch (e) {
      print('获取NBA球队排名失败: $e');
      return [];
    }
  }

  /// 搜索NBA相关内容
  static Future<List<dynamic>> searchNbaContent(String query) async {
    try {
      // 模拟搜索功能
      await Future.delayed(const Duration(milliseconds: 600));
      
      // 这里可以整合多个数据源的搜索结果
      final allResults = <dynamic>[];
      
      // 添加新闻搜索结果
      final news = await fetchNews();
      final matchedNews = news.where((n) => n.title.toLowerCase().contains(query.toLowerCase())).toList();
      allResults.addAll(matchedNews);
      
      // 添加集锦搜索结果
      final highlights = await fetchHighlights();
      final matchedHighlights = highlights.where((h) => h.title.toLowerCase().contains(query.toLowerCase())).toList();
      allResults.addAll(matchedHighlights);
      
      // 添加纪录片搜索结果
      final docs = await fetchDocumentaries();
      final matchedDocs = docs.where((d) => d.title.toLowerCase().contains(query.toLowerCase())).toList();
      allResults.addAll(matchedDocs);
      
      return allResults;
    } catch (e) {
      print('搜索NBA内容失败: $e');
      return [];
    }
  }

  /// 获取直播源的真实播放地址（需要根据具体平台解析）
  static Future<String?> getRealPlayUrl(String sourceUrl) async {
    try {
      // 这里应该实现具体的直播源解析逻辑
      // 对于不同的直播平台（JRS、24小时直播等）需要不同的解析方法
      
      if (sourceUrl.contains('jrszb.com')) {
        // JRS直播源解析逻辑
        return await _parseJrsLiveUrl(sourceUrl);
      } else if (sourceUrl.contains('24zb.com')) {
        // 24小时直播源解析逻辑
        return await _parse24zbLiveUrl(sourceUrl);
      } else if (sourceUrl.contains('hupu.com')) {
        // 虎扑直播源解析逻辑
        return await _parseHupuLiveUrl(sourceUrl);
      }
      
      return sourceUrl; // 默认返回原URL
    } catch (e) {
      print('解析直播源失败: $e');
      return null;
    }
  }

  // 私有方法：解析不同平台的直播源
  static Future<String> _parseJrsLiveUrl(String url) async {
    // 实际项目中应该调用JRS直播的API来获取真实播放地址
    return url;
  }

  static Future<String> _parse24zbLiveUrl(String url) async {
    // 实际项目中应该调用24小时直播的API来获取真实播放地址
    return url;
  }

  static Future<String> _parseHupuLiveUrl(String url) async {
    // 实际项目中应该调用虎扑直播的API来获取真实播放地址
    return url;
  }

  /// 获取NBA视频播放地址
  static Future<String?> getVideoPlayUrl(String videoId) async {
    try {
      final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
      final url = Uri.parse(
          'https://api.nba.cn/cms/v1/video/playurl?'
          'app_key=tiKB2tNdncnZFPOi&'
          'app_version=1.1.0&'
          'channel=NBA&'
          'device_id=c263274b75182ba88d82184208ee88a2&'
          'install_id=2023821643&'
          'network=N%2FA&'
          'os_type=3&'
          'os_version=1.0.0&'
          'quality=hd&'  // 默认请求高清质量
          'sign=sign_v2&'
          'sign2=0576745EB1E18C8BA6BDCB1744B0FF5FE30A6FAD7589D951D2185E102FF88011&'
          't=$timestamp&'
          'vid=$videoId'
      );
  
      final response = await http.get(url, headers: _headers)
          .timeout(const Duration(seconds: 15));

      if (response.statusCode == 200) {
        final json = jsonDecode(response.body);
        // 检查API响应状态
        if (json['code'] != 0) {
          print('NBA视频播放地址API错误: ${json['msg']}');
          
          // 处理签名错误
          if (json['code'] == 40003) {
            print('签名校验失败，可能需要更新签名参数');
          }
          
          return null;
        }
        
        final data = json['data'];
        if (data == null) return null;
        
        // 解析播放地址 - 根据新的API响应格式，字段名为 'url'
        final String? playUrl = data['url']?.toString();
        
        if (playUrl != null && playUrl.isNotEmpty) {
          return playUrl;
        } else {
          print('未找到有效的播放地址');
          return null;
        }
      } else {
        print('获取NBA视频播放地址失败: HTTP ${response.statusCode}');
        return null;
      }
    } catch (e) {
      print('获取NBA视频播放地址失败: $e');
      return null;
    }
  }

  /// 从NBA中国官网获取新闻
  static Future<List<NbaNews>> _fetchNbaCnNews(int page,  int limit) async {
    //默认page为1，limit为10
    page = page > 0 ? page : 1;
    limit = limit > 0 ? limit : 10;
    try {
      final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
      final url = Uri.parse(
          'https://api.nba.cn/cms/v1/news/hot_news?'
          'app_key=tiKB2tNdncnZFPOi&'
          'app_version=1.1.0&'
          'channel=NBA&'
          'device_id=c263274b75182ba88d82184208ee88a2&'
          'install_id=2023821643&'
          'network=N%2FA&'
          'os_type=3&'
          'os_version=1.0.0&'
          'page_no=$page&'
          'page_size=$limit&'
          'sign=sign_v2&'
          'sign2=0576745EB1E18C8BA6BDCB1744B0FF5FE30A6FAD7589D951D2185E102FF88011&'
          't=$timestamp'
      );
      print('获取NBA新闻url: $url');
  
      final response = await http.get(url, headers: _headers)
          .timeout(const Duration(seconds: 15));

      if (response.statusCode == 200) {
        return NbaDataSourceParser.parseNbaCnNews(response.body);
      }
    } catch (e) {
      print('NBA中国新闻数据获取失败: $e');
    }
    return [];
  }

  /// 获取NBA新闻详情
  static Future<NbaNewsDetail> fetchNewsDetail(String newsId) async {
    try {
      final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
      final url = Uri.parse(
          'https://api.nba.cn/cms/v2/news/info?'
          'app_key=tiKB2tNdncnZFPOi&'
          'app_version=1.1.0&'
          'channel=NBA&'
          'device_id=c263274b75182ba88d82184208ee88a2&'
          'install_id=2023821643&'
          'network=N%2FA&'
          'news_id=$newsId&'
          'os_type=3&'
          'os_version=1.0.0&'
          'sign=sign_v2&'
          'sign2=0576745EB1E18C8BA6BDCB1744B0FF5FE30A6FAD7589D951D2185E102FF88011&'
          't=$timestamp'
      );
      print('获取NBA新闻详情url: $url');
  
      final response = await http.get(url, headers: _headers)
          .timeout(const Duration(seconds: 15));

      if (response.statusCode == 200) {
        final json = jsonDecode(response.body);
        if (json['code'] == 0 && json['data'] != null) {
          return NbaNewsDetail.fromJson(json['data']);
        } else {
          throw Exception('API返回错误: ${json['message'] ?? "未知错误"}');
        }
      } else {
        throw Exception('HTTP请求失败: ${response.statusCode}');
      }
    } catch (e) {
      print('获取NBA新闻详情失败: $e');
      rethrow;
    }
  }
}